package com.phkj.qdh.ui.dialog

import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.contrarywind.view.WheelView
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopupext.listener.ISelectTimeCallback
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import com.lxj.xpopupext.view.WheelTime
import com.phkj.qdh.R
import java.text.ParseException
import java.util.Calendar

/**
 * 时间选择器
 */
class MyTimeSelectDialog(context: Context) : BottomPopupView(context) {

    private var mode = TimePickerPopup.Mode.YMD

    private val isLunar = false //是否是农历

    private var startYear = 0
    private var endYear = 0
    private var itemsVisibleCount = 3
    private var itemTextSize = 14
    private var date = Calendar.getInstance()
    private var startDate: Calendar? = null
    private var endDate: Calendar? = null
    private var title: String = "请选择日期"
    var dividerColor = -0x2a2a2b //分割线的颜色

    var lineSpace = 2.8f // 条目间距倍数 默认2

    var textColorOut = -0x575758 //分割线以外的文字颜色

    var textColorCenter = -0xd5d5d6 //分割线之间的文字颜色
    private var wheelTime //自定义控件
            : WheelTime? = null
    private lateinit var ivClose: ImageView
    private lateinit var tvTitle: TextView
    private lateinit var btnConfirm: Button
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_my_time_select
    }

    override fun onCreate() {
        super.onCreate()
        btnConfirm = findViewById(R.id.btn_confirm)
        tvTitle = findViewById(R.id.tv_title)
        ivClose = findViewById(R.id.iv_close)
        tvTitle.text = title
        ivClose.setOnClickListener {
            if (timePickerListener != null) timePickerListener?.onCancel()
            dismiss()
        }

        btnConfirm.setOnClickListener {
            if (timePickerListener != null) {
                try {
                    val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                    if (System.currentTimeMillis()>date.time){
                        ToastUtils.show("选择时间必须大于当前时间")
                        return@setOnClickListener
                    }
                    timePickerListener!!.onTimeConfirm(date, it)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            }
            dismiss()
        }

        initWheelTime(findViewById<View>(R.id.timepicker) as LinearLayout)
        if (popupInfo.isDarkTheme) {
            applyDarkTheme()
        } else {
            applyLightTheme()
        }
    }

    private fun initWheelTime(linearLayout: LinearLayout) {
        wheelTime = WheelTime(linearLayout, mode2type(), Gravity.CENTER, itemTextSize)
        if (timePickerListener != null) {
            wheelTime?.setSelectChangeCallback(ISelectTimeCallback {
                try {
                    val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                    timePickerListener!!.onTimeChanged(date)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            })
        }

        wheelTime?.isLunarMode = isLunar

        if (startYear != 0 && endYear != 0 && startYear <= endYear) {
            applyYear()
        }

        //若手动设置了时间范围限制
        if (startDate != null && endDate != null) {
            require(startDate!!.timeInMillis <= endDate!!.timeInMillis) { "startDate can't be later than endDate" }
            applyDateRange()
        } else if (startDate != null) {
            require(startDate!![Calendar.YEAR] >= 1900) { "The startDate can not as early as 1900" }
            applyDateRange()
        } else if (endDate != null) {
            require(endDate!![Calendar.YEAR] <= 2100) { "The endDate should not be later than 2100" }
            applyDateRange()
        } else { //没有设置时间范围限制，则会使用默认范围。
            applyDateRange()
        }

        setTime()
        if (showLabel) wheelTime?.setLabels(
            resources.getString(R.string._xpopup_ext_year),
            resources.getString(R.string._xpopup_ext_month),
            resources.getString(R.string._xpopup_ext_day),
            resources.getString(R.string._xpopup_ext_hours),
            resources.getString(R.string._xpopup_ext_minutes),
            resources.getString(R.string._xpopup_ext_seconds)
        )

        wheelTime!!.run {
            setItemsVisible(itemsVisibleCount)
            setAlphaGradient(true)
            setCyclic(true)
            setDividerColor(if (popupInfo.isDarkTheme) Color.parseColor("#444444") else dividerColor)
            setDividerType(WheelView.DividerType.FILL)
            setLineSpacingMultiplier(lineSpace)
            setTextColorOut(textColorOut)
            setTextColorCenter(if (popupInfo.isDarkTheme) Color.parseColor("#CCCCCC") else textColorCenter)
            isCenterLabel(false)
        }
    }

    var showLabel = true

    private fun mode2type(): BooleanArray? {
        return when (mode) {
            TimePickerPopup.Mode.Y -> booleanArrayOf(true, false, false, false, false, false)
            TimePickerPopup.Mode.YM -> booleanArrayOf(true, true, false, false, false, false)
            TimePickerPopup.Mode.YMD -> booleanArrayOf(true, true, true, false, false, false)
            TimePickerPopup.Mode.YMDH -> booleanArrayOf(true, true, true, true, false, false)
            TimePickerPopup.Mode.YMDHM -> booleanArrayOf(true, true, true, true, true, false)
            else -> booleanArrayOf(true, true, true, true, true, true)
        }
    }

    fun setMode(mode: TimePickerPopup.Mode?): MyTimeSelectDialog {
        this.mode = mode!!
        return this
    }

    var timePickerListener: TimePickerListener? = null
    fun setTimePickerListener(listener: TimePickerListener?): MyTimeSelectDialog {
        timePickerListener = listener
        return this
    }

    fun setItemTextSize(textSize: Int): MyTimeSelectDialog {
        itemTextSize = textSize
        return this
    }

    fun setItemsVisibleCount(itemsVisibleCount: Int): MyTimeSelectDialog {
        this.itemsVisibleCount = itemsVisibleCount
        return this
    }

    fun setLineSpace(lineSpace: Float): MyTimeSelectDialog {
        this.lineSpace = lineSpace
        return this
    }

    /**
     * 是否显示年月日字样
     * @return
     */
    fun setShowLabel(showLabel: Boolean): MyTimeSelectDialog {
        this.showLabel = showLabel
        return this
    }

    /**
     * 设置默认时间
     */
    fun setDefaultDate(date: Calendar): MyTimeSelectDialog {
        this.date = date
        return this
    }

    fun setTitle(s: String): MyTimeSelectDialog {
        this.title = s
        return this
    }

    /**
     * 设置年份范围
     */
    fun setYearRange(startYear: Int, endYear: Int): MyTimeSelectDialog {
        this.startYear = startYear
        this.endYear = endYear
        return this
    }


    /**
     * 设置可以选择的时间范围
     */
    fun setDateRange(startDate: Calendar, endDate: Calendar?): MyTimeSelectDialog {
        this.startDate = startDate
        this.endDate = endDate
        return this
    }

    private fun applyYear() {
        wheelTime?.startYear = startYear
        wheelTime?.endYear = endYear
    }

    private fun applyDateRange() {
        wheelTime?.setRangDate(startDate, endDate)
        initDefaultSelectedDate()
    }

    private fun initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (startDate != null && endDate != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (date == null || date.timeInMillis < startDate!!.timeInMillis || date.timeInMillis > endDate!!.timeInMillis) {
                date = startDate
            }
        } else if (startDate != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            date = startDate
        } else if (endDate != null) {
            date = endDate
        }
    }


    /**
     * 设置选中时间,默认选中当前时间
     */
    private fun setTime() {
        val year: Int
        val month: Int
        val day: Int
        val hours: Int
        val minute: Int
        val seconds: Int
        val calendar = Calendar.getInstance()
        if (date == null) {
            calendar.timeInMillis = System.currentTimeMillis()
            year = calendar[Calendar.YEAR]
            month = calendar[Calendar.MONTH]
            day = calendar[Calendar.DAY_OF_MONTH]
            hours = calendar[Calendar.HOUR_OF_DAY]
            minute = calendar[Calendar.MINUTE]
            seconds = calendar[Calendar.SECOND]
        } else {
            year = date[Calendar.YEAR]
            month = date[Calendar.MONTH]
            day = date[Calendar.DAY_OF_MONTH]
            hours = date[Calendar.HOUR_OF_DAY]
            minute = date[Calendar.MINUTE]
            seconds = date[Calendar.SECOND]
        }
        wheelTime!!.setPicker(year, month, day, hours, minute, seconds)
    }


    companion object {
        /**
         *
         */
        @JvmStatic
        fun newInstance(context: Context) = MyTimeSelectDialog(context).apply {

        }
    }
}
